'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');
class AccountController extends Controller {
  // 发送激活邮件
  async pushRegEmailCode() {
    const { app,ctx } = this;
    if(app.validator.validate({email:'string'},ctx.request.body)){
        return ctx.helper.resError('邮箱不能为空');
    }
    if(!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(ctx.request.body.email))){
        return ctx.helper.resError('邮箱格式错误');
    }
    let user = await ctx.service.user.account.getEmaildetail(ctx.request.body);
    if(user){
        return ctx.helper.resError('邮箱已被注册');
    }
    let detail = await ctx.service.user.account.getRegEmailCode(ctx.request.body);
    if(detail&&new Date().getTime()-detail.pushTime<60000){
        return ctx.helper.resError('距上次发送时间未超过1分钟');
    }
    let email = ctx.request.body.email;
    let code = '';
    for(let i=0;i<6;i++){
        code += Math.floor(Math.random()*10);
    }
    try{
        await ctx.helper.pushEmail({
            email:email,
            subject:'验证你的注册电子邮件',
            html:`
            <p>你好！</p>
            <p>你的验证码是：<strong style="color: #ff4e2a;">${code}</strong></p>
            <p>***该验证码30分钟内有效***</p>`
        })
    }catch(e){
        return ctx.helper.resError('发送失败');
    }
    let result = await ctx.service.user.account.saveRegEmailCode({
        email:email,
        code:code
    });
    if(result.id){
        return ctx.helper.resSuccess('发送成功');
    }else{
        return ctx.helper.resError('发送失败');
    }
  }
  // 注册
  async register() {
    const { app,ctx } = this;
    if(app.validator.validate({email:'string'},ctx.request.body)){
        return ctx.helper.resError('邮箱不能为空');
    }
    if(app.validator.validate({code:'string'},ctx.request.body)){
        return ctx.helper.resError('验证码不能为空');
    }
    if(app.validator.validate({nickname:'string'},ctx.request.body)){
        return ctx.helper.resError('昵称不能为空');
    }
    if(app.validator.validate({password:'string'},ctx.request.body)){
        return ctx.helper.resError('密码不能为空');
    }
    if(app.validator.validate({password2:'string'},ctx.request.body)){
        return ctx.helper.resError('确认密码不能为空');
    }
    if(ctx.request.body.password!=ctx.request.body.password2){
        return ctx.helper.resError('确认密码不一致');
    }
    let user = await ctx.service.user.account.getEmaildetail(ctx.request.body);
    if(user){
        return ctx.helper.resError('邮箱已被注册');
    }
    let detail = await ctx.service.user.account.getRegEmailCode(ctx.request.body);
    if(!detail){
        return ctx.helper.resError('验证码未发送');
    }
    if(new Date().getTime()>detail.verifyTime){
        return ctx.helper.resError('验证码已过期');
    }
    if(detail.code!=ctx.request.body.code){
        return ctx.helper.resError('验证码错误');
    }
    ctx.request.body.password = crypto.createHash('md5').update(`${app.config.crypto.secret}${ctx.request.body.password}`).digest('hex');
    let result = await ctx.service.user.account.register(ctx.request.body);
    if(result.id){
      return ctx.helper.resSuccess('注册成功');
    }else{
      return ctx.helper.resError('添加失败');
    }
  }

  // 登录
  async login() {
    const { app,ctx } = this;
    if(app.validator.validate({account:'string'},ctx.request.body)){
      return ctx.helper.resError('账号不能为空');
    }
    if(app.validator.validate({password:'string'},ctx.request.body)){
      return ctx.helper.resError('密码不能为空');
    }
    ctx.request.body.password = crypto.createHash('md5').update(`${app.config.crypto.secret}${ctx.request.body.password}`).digest('hex');
    let result = await ctx.service.user.account.login(ctx.request.body);
    if(result){
      if(result.status==1){
        return ctx.helper.resSuccess(
          app.jwt.sign({
            id:result.id,
            utype:'user'
          }, this.app.config.jwt.secret, { expiresIn: '604800000s' })
        );
      }else{
        return ctx.helper.resError('账号被禁用');
      }
    }else{
      return ctx.helper.resError('账号或密码错误');
    }
  }

  // 账号详情
  async getInfo(){
    const { ctx } = this;
    let detail = await ctx.service.user.account.info();
    if(detail){
      return ctx.helper.resSuccess(detail);
    }else{
      return ctx.helper.resError('获取信息失败');
    }
  }

  // 账号信息修改
  async editInfo(){
    const { app,ctx } = this;
    if(app.validator.validate({nickname:'string'},ctx.request.body)){
      return ctx.helper.resError('昵称不能为空');
    }
    let result = await ctx.service.user.account.editInfo(ctx.request.body);
    if(result[0]){
      return ctx.helper.resSuccess(true);
    }else{
      return ctx.helper.resError('更新失败');
    }
  }

  // 修改密码
  async editPassword(){
    const { app,ctx } = this;
    if(app.validator.validate({password:'string'},ctx.request.body)){
      return ctx.helper.resError('新密码不能为空');
    }
    if(app.validator.validate({password2:'string'},ctx.request.body)){
      return ctx.helper.resError('确认密码不能为空');
    }
    if(ctx.request.body.password!=ctx.request.body.password2){
      return ctx.helper.resError('确认密码不一致');
    }
    ctx.request.body.password = crypto.createHash('md5').update(`${app.config.crypto.secret}${ctx.request.body.password}`).digest('hex');
    let result = await ctx.service.user.account.editPassword(ctx.request.body);
    if(result[0]){
      return ctx.helper.resSuccess(true);
    }else{
      return ctx.helper.resError('更新失败');
    }
  }

  // 发送找回密码邮件
  async pushFindEmailCode() {
    const { app,ctx } = this;
    if(app.validator.validate({email:'string'},ctx.request.body)){
      return ctx.helper.resError('邮箱不能为空');
    }
    if(!(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(ctx.request.body.email))){
      return ctx.helper.resError('邮箱格式错误');
    }
    let detail = await ctx.service.user.account.getFindEmailCode(ctx.request.body);
    if(detail&&new Date().getTime()-detail.pushTime<60000){
      return ctx.helper.resError('距上次发送时间未超过1分钟');
    }
    let email = ctx.request.body.email;
    let code = '';
    for(let i=0;i<6;i++){
      code += Math.floor(Math.random()*10);
    }
    try{
      await ctx.helper.pushEmail({
        email:email,
        subject:'验证你的找回密码电子邮件',
        html:`
            <p>你好！</p>
            <p>你的验证码是：<strong style="color: #ff4e2a;">${code}</strong></p>
            <p>***该验证码30分钟内有效***</p>`
      })
    }catch(e){
      return ctx.helper.resError('发送失败');
    }
    let result = await ctx.service.user.account.saveFindEmailCode({
      email:email,
      code:code
    });
    if(result.id){
      return ctx.helper.resSuccess('发送成功');
    }else{
      return ctx.helper.resError('发送失败');
    }
  }

  // 找回密码
  async findPassword(){
    const { app,ctx } = this;
    if(app.validator.validate({email:'string'},ctx.request.body)){
      return ctx.helper.resError('邮箱不能为空');
    }
    if(app.validator.validate({code:'string'},ctx.request.body)){
      return ctx.helper.resError('验证码不能为空');
    }
    if(app.validator.validate({password:'string'},ctx.request.body)){
      return ctx.helper.resError('密码不能为空');
    }
    if(app.validator.validate({password2:'string'},ctx.request.body)){
      return ctx.helper.resError('确认密码不能为空');
    }
    if(ctx.request.body.password!=ctx.request.body.password2){
      return ctx.helper.resError('确认密码不一致');
    }
    let detail = await ctx.service.user.account.getFindEmailCode(ctx.request.body);
    if(!detail){
      return ctx.helper.resError('验证码未发送');
    }
    if(new Date().getTime()>detail.verifyTime){
      return ctx.helper.resError('验证码已过期');
    }
    if(detail.code!=ctx.request.body.code){
      return ctx.helper.resError('验证码错误');
    }
    ctx.request.body.password = crypto.createHash('md5').update(`${app.config.crypto.secret}${ctx.request.body.password}`).digest('hex');
    let result = await ctx.service.user.account.findPassword(ctx.request.body);
    if(result[0]){
      return ctx.helper.resSuccess(true);
    }else{
      return ctx.helper.resError('更新失败');
    }
  }
}

module.exports = AccountController;
